//
//  HomeTableViewController.swift
//  weiboxiangmu
//
//  Created by wei_jingyun on 15/6/23.
//  Copyright © 2015年 wei_jingyun. All rights reserved.
//

import UIKit
import SVProgressHUD


class HomeTableViewController: BaseTableViewController {
    
    // 定义模型数组 每次给模型数组赋值时就刷新表格
     var statusesList : [Status]? {
        didSet {
            tableView.reloadData()
        }
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
       visitotView?.showVisitorView("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
       
        // 只有登陆成功才执行以下代码
        if !userState {
            return
        }

        // 设置导航栏和 tableView
        setupNavigationBar()
        steupTableView()
    }
    
    // 关注用户
    func focusUser(){
        Debug.LogFunc()
    }
    
    // 中间title被点击 弹出控制器
    func titleClick(){
        Debug.LogFunc()
        let btn = navigationItem.titleView as! UIButtonExchange
        btn.selected = !btn.selected
    }
    
    // 弹出二维码
    func showQRCode(){
        Debug.LogFunc()
    }
    
    // MARK: 加载微博数据 ture  为下拉 false 为上拉
    func loadData(refresh : Bool){
        weak var weakSelf = self
        var since_id = statusesList?.first?.id ?? 0
        var max_id =   statusesList?.last?.id ?? 0
        if refresh {
            max_id = 0
        }else {
            since_id = 0
        }
      
        Status.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            // 收回
            weakSelf?.refreshControl?.endRefreshing()
            
            if statuses == nil || error != nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力或服务器拒绝访问")
                return
            }
            
            // 为空 就直接赋值
            if weakSelf!.statusesList == nil {
                weakSelf!.statusesList = statuses
                return
            }

            // 判断上拉下拉拼接 数组
            if refresh {
                weakSelf!.statusesList! = statuses! + weakSelf!.statusesList!
            }else {
                weakSelf!.statusesList! = weakSelf!.statusesList! + statuses!
            }
            
            Debug.Log("\(self.statusesList?.last?.id)  \(statuses?.count)" )
        }
    }
    
    // MARK: tableView 相关设置
    private func steupTableView(){
        // 注册cell
        tableView.registerClass(HomeStatusNomalCell.self, forCellReuseIdentifier: HomeCellOne)
        tableView.registerClass(HomeStatusForwardCell.self, forCellReuseIdentifier: HomeCellTwo)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
         weak var weakSelf = self
        self.refreshControl = JYRefreshControl().refreshing({ () -> () in
            weakSelf?.loadData(true)
        })
        
        loadData(true)
    }
    

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 未登录状态执行旋转动画
        visitotView?.startAn()
    }
    
    // MARK: - 数据原方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesList?.count ?? 0
    }
  
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statusesList![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCell.StatusCellID(status), forIndexPath: indexPath) as! HomeTableViewCell
        
        // 数组取数时必须保证 ！否则无法调用模型属性 报错
        cell.status = status
        
        // 判断是不是最后一行如果是 就加载新数据
        if indexPath.row + 3 == statusesList?.count {
            loadData(false)
        }
        
        return cell
    }
    
    // 高度设置
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 取到对应模型
        let status = statusesList![indexPath.row]
        
        // 判断是否已有行高
        if status.rowHeight > 0 {
//            Debug.LogN("返回缓存行高...\(status.rowHeight)")
            return status.rowHeight
        }
        
        let str = HomeTableViewCell.StatusCellID(status)
        // 获取 cell 该cell 只做计算用马上就会丢弃 不要使用 forIndexPath 方法
        // 如果从缓存取也可能会因cell重用照成一些问题 重新建一个最好
        let cell = str == HomeCellOne ? HomeStatusNomalCell() : HomeStatusForwardCell()
        return cell.rowHeight(status)
    }
    
    // 设置导航条
    private func setupNavigationBar(){
        // 1.设置按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: nil, target: self, actionName: "focusUser")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: nil, target: self, actionName: "showQRCode")
        
        // 2.中间title
        let  btn = UIButtonExchange.button(sharedUserAccount!.name!, imageName: "navigationbar_arrow_down",target: self, actionName: "titleClick")
        btn.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected)
        btn.adjustsImageWhenHighlighted = false
        btn.titleLabel?.font = UIFont.systemFontOfSize(17)
        
        navigationItem.titleView = btn
    }
    
   
    
}
